package cn.edu.sbs.talent.shiro.mapper;

import cn.edu.sbs.talent.common.mapper.BaseMapper;
import cn.edu.sbs.talent.shiro.entity.Permission;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 权限 Mapper
 *
 * @author ctidy
 * @since 2021/1/7
 */
public interface PermissionMapper extends BaseMapper<Permission> {

    /**
     * 按账户ID查询权限列表
     *
     * @param accountId 账户ID
     * @return 权限列表
     */
    @Select("SELECT DISTINCT `p`.* FROM `t_permission` AS `p` " +
            "JOIN `t_role_permission` AS `rp` ON `p`.`id` = `rp`.`permission_id` " +
            "JOIN `t_role` AS `r` ON `r`.`id` = `rp`.`role_id` " +
            "JOIN `t_account_role` AS `ar` ON `ar`.`role_id` = `r`.`id` " +
            "WHERE `ar`.`account_id` = #{accountId} " +
            "  AND `p`.`deleted` = 0 " +
            "  AND `rp`.`deleted` = 0 " +
            "  AND `r`.`deleted` = 0 " +
            "  AND `ar`.`deleted` = 0 ")
    List<Permission> selectBatchByAccountId(long accountId);

    /**
     * 按用户名查询权限列表
     *
     * @param username 用户名
     * @return 权限列表
     */
    @Select("SELECT DISTINCT `p`.* FROM `t_permission` AS `p` " +
            "JOIN `t_role_permission` AS `rp` ON `p`.`id` = `rp`.`permission_id` " +
            "JOIN `t_role` AS `r` ON `r`.`id` = `rp`.`role_id` " +
            "JOIN `t_account_role` AS `ar` ON `ar`.`role_id` = `r`.`id` " +
            "JOIN `t_account` AS `a` ON `a`.`id` = `ar`.`account_id` " +
            "WHERE `a`.`username` = #{username} " +
            "  AND `p`.`deleted` = 0 " +
            "  AND `rp`.`deleted` = 0 " +
            "  AND `r`.`deleted` = 0 " +
            "  AND `ar`.`deleted` = 0 " +
            "  AND `a`.`deleted` = 0 ")
    List<Permission> selectBatchByAccountUsername(String username);

    /**
     * 按角色ID查询权限列表
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Select("SELECT DISTINCT `p`.* FROM `t_permission` AS `p` " +
            "JOIN `t_role_permission` AS `rp` ON `p`.`id` = `rp`.`permission_id` " +
            "WHERE `rp`.`role_id` = #{roleId} " +
            "  AND `p`.`deleted` = 0 " +
            "  AND `rp`.`deleted` = 0 ")
    List<Permission> selectBatchByRoleId(long roleId);

    /**
     * 按角色名查询权限列表
     *
     * @param name 角色名
     * @return 权限列表
     */
    @Select("SELECT DISTINCT `p`.* FROM `t_permission` AS `p` " +
            "JOIN `t_role_permission` AS `rp` ON `p`.`id` = `rp`.`permission_id` " +
            "JOIN `t_role` AS `r` ON `r`.`id` = `rp`.`role_id` " +
            "WHERE `r`.`name` = #{name} " +
            "  AND `p`.`deleted` = 0 " +
            "  AND `rp`.`deleted` = 0 " +
            "  AND `r`.`deleted` = 0 ")
    List<Permission> selectBatchByRoleName(String name);

    // TODO t_permission 与 t_permission_role 级联删除

}
